#include<iostream>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<cstring>
#include<string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
int main()
{
    int sockfd;
    struct sockaddr_in servadder,cliaddr;
    socklen_t cliaddrlen = sizeof(cliaddr);
    char buffer[1024];
    sockfd= socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        perror("sockert creation failed");
        exit(EXIT_FAILURE);
    }
    memset(&servadder,0,sizeof(servadder));
    servadder.sin_family=AF_INET;
    servadder.sin_addr.s_addr=INADDR_ANY;
    servadder.sin_port=htons(8080);

    if(bind(sockfd,(const struct sockaddr*)&servadder,sizeof(servadder))<0)
    {
        perror("socket bind failed");
        exit(EXIT_FAILURE);
    }
    std::cout<<"Server is listening on port 8080..."<<std::endl;

    while(true)
    {
        ssize_t n =recvfrom(sockfd,buffer,sizeof(buffer),0,
                            (struct sockaddr*)&cliaddr,&cliaddrlen);
        if(n<0)
        {
            perror("recvfrom failed");
            continue;
        }
        buffer[n]='\0';
        std::cout<<"Received request from client:"<<buffer<<std::endl;

        std::string response = "Hello from server";

        if(sendto(sockfd,response.c_str(),response.length(),0,
                (const struct sockaddr *)&cliaddr, cliaddrlen)<0)
                {
                    perror("sendto failed");
                }
    }

    close(sockfd);
    return 0;
    

}